<!-- 班级动态 -->
<script setup lang="ts">
import MpHtml from 'mp-html/src/uni-app/components/mp-html/mp-html.vue'
import { useLoadMore } from 'vue-request'
import { fetchClassNewsAPI } from '@/apis/fetchClassNews'
import { useUserInfoStore } from '@/store/userInfo'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 班级 id
const classId = ref('')

// 分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore, refresh } = useLoadMore<LoadMoreData<ClassNews>>(
  fetchClassNews,
  { isNoMore: d => d?.list.length === d?.total },
)

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

onLoad((options) => {
  if (options && options.class_id) {
    classId.value = options.class_id
    refresh()
  }
  else { uni.showToast({ title: '页面加载错误：未获取到班级id', icon: 'none' }) }
})
onReachBottom(() => loadMore())

async function fetchClassNews(d?: LoadMoreData<ClassNews>): Promise<LoadMoreData<ClassNews>> {
  // 缺少必要参数，先不执行
  if (!classId.value)
    return { list: [], page: 0, total: 0 }

  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  const res = await fetchClassNewsAPI({
    id: classId.value,
    page: _page.toString(),
    limit: '10',
  }, userInfoStore.userInfo!.token!)

  return {
    list: res.data?.data.data || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

function handleTapNews(id: string) {
  router.push({
    name: 'classNewsDetail',
    params: { id },
  })
}
</script>

<template>
  <Spacer height="20" />
  <uv-list :custom-style="{ background: 'transparent' }">
    <uv-list-item v-for="news in dataList" :key="news.id" :custom-style="{ borderRadius: '20rpx', marginBottom: '20rpx' }">
      <view class="rounded-20rpx bg-white p-25rpx card-shadow" @tap="handleTapNews(news.id.toString())">
        <view class="text-28rpx text-#666666 leading-40rpx">
          {{ news.create_time || '未知时间' }}
        </view>
        <Spacer height="24" />
        <Divider width="650" />
        <Spacer height="24" />
        <view class="text-32rpx text-black font-medium leading-45rpx">
          {{ news.title || '未知标题' }}
        </view>
        <Spacer height="20" />
        <view class="max-h-80rpx overflow-hidden whitespace-pre-line break-words text-wrap text-26rpx text-#333333 leading-40rpx">
          {{ news.introduce || '未知内容' }}
        </view>
      </view>
    </uv-list-item>
    <!-- 加载更多 -->
    <uv-load-more v-if="dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
  </uv-list>
  <Spacer height="240" />
  <PageDefault v-if="dataList.length === 0">
    暂无班级动态
  </PageDefault>
  <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'classNews'
style:
  navigationBarTitleText: '班级动态'
</route>
